<?php

/**
 * Controller/InstructionPaieController.php
 */

namespace RHX\Controller;

use Zend\View\Model\ViewModel;
use RHX\Model\Object\InstructionPaie;

class InstructionPaieController extends RHXController {
    /**
     *
     * @var \RHX\Model\Manager\InstructionManager
     */
    protected $manager = null;
    
    /**
     *
     * @var boolean
     */
    private $postDefined = false;
    
    protected $site = null;
    protected $periode = null;

    /**
     * Page d'index
     *
     * @return \Zend\View\Model\ViewModel
     */
    public function indexAction() {
	$this->thePost();
	// Vue
	$index		 = new ViewModel();
	$index->setTemplate('rhx/instruction-paie/index.phtml');
	$loadIndex	 = $this->loadIndexAction();
	$loadIndex->setVariables(array(
	    'site'		 => $this->site,
	    'periode'	 => $this->periode,
	));
	$index->addChild($loadIndex, 'loadIndex');
	$index->setVariables(array(
	    'site'		 => $this->site,
	    'periode'	 => $this->periode,
	));
	$this->layout('layout/rhx2');

	return $index;
    }

    /**
     * Structure général du contenu de la page d'index
     *
     * @return \Zend\View\Model\ViewModel
     */
    public function loadIndexAction() {
	$this->thePost();
	$post = $this->getRequest()->getPost();
	$loadIndex = new ViewModel();
	$loadIndex->setVariable('periode', $this->getManager()->getPeriode($post->periode));
	$loadIndex->setVariable('site', $this->getManager()->getSite($post->site));
	$loadIndex->setTemplate('rhx/instruction-paie/load-index.phtml');
	$planningContent	 = $this->loadPlanningContentAction();
	$transfertContent	 = $this->loadTransfertContentAction();
	$loadIndex->addChild($planningContent, 'planningContent');
	$loadIndex->addChild($transfertContent, 'transfertContent');
	$this->layout('layout/ajax');
//	$this->changeSite($post->site);
//	$this->changePeriode($post->periode);

	return $loadIndex;
    }
    
    public function loadIndexTotalAction(){
	$post = $this->getPost();
	$loadTotal = new ViewModel();
	$loadTotal->setVariable('periode', $this->getManager()->getPeriode($post->periode));
	$loadTotal->setVariable('site', $this->getManager()->getSite($post->site));
	$loadTotal->setTemplate('rhx/instruction-paie/load-index.phtml');
	$planningContent	 = $this->loadPlanningContentAction();
	$loadTotal->addChild($planningContent, 'planningContent');
	$this->layout('layout/ajax');
	return $loadTotal;
    }

    /**
     * Contenu du corps du tableau
     *
     * @return \Zend\View\Model\ViewModel
     */
    public function loadPlanningContentAction() {
	$this->thePost();
	$post		 = $this->getRequest()
		->getPost();
	$instructions	 = $this->getManager()->loadPlanningContent($post);
	$planningContent = new ViewModel(array(
	    'instructions' => $instructions,
	    'periode' => $post->periode,
	    'site' => $post->site,
	    'manager' => $this->getManager(),
	    'refMutuelle' => $this->getManager()->getMutuelleReference(),
	    'action' => (int)$post->action,
	));
	$planningContent->setTemplate('rhx/instruction-paie/planning-content.phtml');
	//$this->layout('layout/ajax');

	return $planningContent;
    }

    /**
     * Contenu du bas du tableau
     *
     * @return \Zend\View\Model\ViewModel
     */
    public function loadTransfertContentAction() {
	$this->thePost();
	$transfertContent = new ViewModel();
	$transfertContent->setTemplate('rhx/instruction-paie/transfert-content.phtml');
	$this->layout('layout/ajax');

	return $transfertContent;
    }
    
    /**
     * Manager des Instructions de paie
     * 
     * @return \RHX\Model\Manager\InstructionManager
     */
    public function getManager(){
	if(is_null($this->manager)){
	    $this->manager = new \RHX\Model\Manager\InstructionManager($this->getAdapter());
	}
	return $this->manager;
    }

    /**
     * Traitement et manipulation des données en POST
     */
    private function thePost(){
	if($this->postDefined) {return;}
	// remplissage du POST
	$post = $this->getRequest()
		->getPost();
	$post->set('action', InstructionPaie::CREATE);

	// paramètres
	$siteId		 = (int) $this->params()
			->fromRoute('id', -1);
	$periodeId	 = (int) $this->params()
			->fromRoute('other1', -1);
	// object
	$site		 = null;
	if ($siteId < 0) {
	    $site = $this->navigation
		    ->offsetGet('site');
	    $post->set('site', $site->id);
	}
	else {
	    $tableSite = new \RHX\Model\Table\SiteTable($this->getAdapter());
	    try {
		$site = $tableSite->get($siteId);
		$this->changeSite($siteId);
		$post->set('site', $siteId);
	    }
	    catch (\Exception $ex) {
		$site = $tableSite->getAll()
			->current();
		$this->changeSite($site->id);
		$post->set('site', $site->id);
	    }
	}
	$periode = null;
	if ($periodeId < 0) {
	    $periode = $this->navigation
		    ->offsetGet('periode');
	    $post->set('periode', $periode->id);
	}
	else {
	    $tablePeriode = new \RHX\Model\Table\PeriodeTable($this->getAdapter());
	    try {
		$periode = $tablePeriode->get($periodeId);
		$this->changePeriode($periodeId);
		$post->set('periode', $periodeId);
	    }
	    catch (\Exception $ex) {
		$periode = $tableSite->getAll()
			->current();
		$this->changePeriode($periode->id);
		$post->set('periode', $periode->id);
	    }
	}
	$this->postDefined = true;
	$this->site = $site;
	$this->periode = $periode;
    }
    
    /**
     * Exporter en Excel
     * 
     * @return array
     */
    public function exportAction(){
	$post = $this->getPost();
	$excel = new \RHX\Model\Manager\ExcelManager($this->getAdapter());
	$excel->load();
	$instr = $this->getManager()->prepareData($post);
	$title = $this->getManager()->prepareTitle($post);
	$excel->fillInformation($title);
	$excel->fillExcel($instr);
	$titre = $title['number'].' - '.'Planning'.$title['site'].$title['periode'];
	$fileName = \RHX\Helper\String::supprAccents($titre).'.xls';
	$excel->save($fileName);
	return new \Zend\View\Model\JsonModel(array(
	    'done' => true,
	    'post' => $post,
	    'excel' => $excel,
	    'fileName' => $fileName,
	    'error' => '',
	));
    }
    
    /**
     * Liste des Primes CP
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function primeCPAction(){
	$data = $this->getManager()
		->getPrimeList(\RHX\Model\Object\Prime::CP);
	return new \Zend\View\Model\JsonModel($data);
    }
    
    /**
     * Liste des Primes Hors CP
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function primeHCPAction(){
	$data = $this->getManager()
		->getPrimeList(\RHX\Model\Object\Prime::HORS_CP);
	return new \Zend\View\Model\JsonModel($data);
    }
    
    /**
     * Récupération des informations de prime
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function primeInfoAction(){
	$post = $this->getPost();
	$data = $this->getManager()
		->getPrime($post->id);
	return new \Zend\View\Model\JsonModel(array('info' => $data,));
    }
    
    /**
     * Exportation du fichier de Synthèse
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function syntheseAction(){
	$post = $this->getPost();
	$excel = new \RHX\Model\Manager\ExcelManager($this->getAdapter());
	$excel->load("synthese2.xls");
	$instr = $this->getManager()->prepareData($post);
	$title = $this->getManager()->prepareTitle($post);
	$excel->fillSyntheseInformation($title);
	$excel->fillSynthese($instr);
	$titre = $title['number'].' - '.'Synthese'.$title['site'].$title['periode'];
	$fileName = \RHX\Helper\String::supprAccents($titre).'.xls';
	$excel->save($fileName);
	return new \Zend\View\Model\JsonModel(array(
	    'done' => true,
	    'filename' => $fileName,
	    'error' => null,
	));
    }
    
    /**
     * Mise à jour des informations
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function updateNumberAction(){
	$post = $this->getPost();
	$pk = $post->pk;
	$name = $post->name;
	$value = \RHX\Helper\Number::parseFloat($post->value);
	$sql = "UPDATE rh_instruction_paie SET $name = $value WHERE id = $pk";
	$result = $this->getAdapter()
		->query($sql)
		->execute();
	$done = false;
	if($result->getAffectedRows() >= 1){
	    $done = true;
	}
	return new \Zend\View\Model\JsonModel(array(
	    'done' => $done,
	    'sql' => $sql,
	));
    }
    
    /**
     * Mise à jour des valeurs
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function updateStringAction(){
	$post = $this->getPost();
	$pk = $post->pk;
	$name = $post->name;
	$value = addslashes($post->value);
	$sql = "UPDATE rh_instruction_paie SET $name = '$value' WHERE id = $pk";
	$result = $this->getAdapter()
		->query($sql)
		->execute();
	$done = false;
	if($result->getAffectedRows() >= 1){
	    $done = true;
	}
	return new \Zend\View\Model\JsonModel(array(
	    'done' => $done,
	    'sql' => $sql,
	));
    }
    
    /**
     * Calcul du salaire
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function salaireAction(){
	$post = $this->getPost();
        
        // Manager - calculator
        $calculator	 = new \RHX\Model\Object\XCalculator($this->getAdapter());
        $instManager     = $this->getManager();
        
        //tables        
        $tablePlanning		 = new \RHX\Model\Table\PlanningSemaineTable($this->getAdapter());
        
        // object
        $instruction    = $instManager->getInstruction($post->id);        
        $periode        = $instruction->getPeriode();
        $employe        = $instruction->getEmploye();
        
        $plannings	= $tablePlanning->getPlanningsByDateRange($employe->matricule, $periode->debut, $periode->fin);
        $isSaved = true;
        $dataInst         = $calculator->calculInstructionPaie($plannings, $employe->matricule, $isSaved);
        $instruction->fill($dataInst);
        
        $salaire_brute = $calculator->calculSalaireBrute($instruction);
        $salaire_brute_synth = $calculator->calculSalaireBruteSynthese($instruction);
	$dataJson = array(
	    'salaire_excel' => $instManager->calculSalaire($post->id),
            'salaire' => $salaire_brute,
            'salaire_synth' => $salaire_brute_synth
                
	);
	return new \Zend\View\Model\JsonModel($dataJson);
    }
    
    /**
     * Insertion d'une nouvelle instruction de paie dans la base de données
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function insertAction(){
        $thisManager = $this->getManager();
	$post = $this->getPost(); 
        
        $instruction = $thisManager->getByMatriculeGroup($post->matricule, $post->group);
        
        if( ! (boolean)$instruction){ // 
            $instruction = $thisManager->insert($post);
        }
        else{ // Si eventuellement une Instruction y est déja attrriubé : on garde    
            ;// do nothing
        }
        
	return new \Zend\View\Model\JsonModel(array('paie' => $instruction ));
    }
    
    /**
     * Liste des sites pour les instructions de paie
     * 
     * @return \Zend\View\Model\JsonModel
     */
    public function siteListeAction(){
	$data = $this->getManager()->siteListe();
	return new \Zend\View\Model\JsonModel($data);
    }
}
